import { createSlice } from '@reduxjs/toolkit'
import { removeToken } from '@/utils'
import { setToken as _setToken, getToken } from '@/utils'
import { loginAPI,getProfileAPI } from '@/apis/user'

const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken() || '',
        userInfo:{}
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(action.payload)
        },
        setuserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfoAndToken(state){
            state.token=''
            state.userInfo={}
            removeToken()
        }
    }
})

// 解构出actionCreater
const { setToken,setuserInfo,clearUserInfoAndToken } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

//完成登录获取token异步方法 
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        dispatch(setToken(res.data.token))
    }
}

//获取个人用户信息异步方法 
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getProfileAPI()
        dispatch(setuserInfo(res.data))
    }
}


export { setToken, fetchLogin,fetchUserInfo,clearUserInfoAndToken }

export default userReducer